package val.to;

import java.io.File;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;

public class Utility {

	public static final boolean DEBUG = true;

	static class FlushedInputStream extends FilterInputStream {
		public FlushedInputStream(InputStream inputStream) {
			super(inputStream);
		}

		@Override
		public long skip(long n) throws IOException {
			long totalBytesSkipped = 0L;
			while (totalBytesSkipped < n) {
				long bytesSkipped = in.skip(n - totalBytesSkipped);
				if (bytesSkipped == 0L) {
					int b = read();
					if (b < 0) {
						break; // we reached EOF
					} else {
						bytesSkipped = 1; // we read one byte
					}
				}
				totalBytesSkipped += bytesSkipped;
			}
			return totalBytesSkipped;
		}
	}

	public static Uri getOutputMediaFileUri(String FolderName) {
		File file = GetOutputMediaFile(FolderName);
		if (file == null)
			return null;

		return Uri.fromFile(file);
	}

	/** Create a File for saving an image */
	private static File GetOutputMediaFile(String FolderName) {
		// To be safe, you should check that the SDCard is mounted
		// using Environment.getExternalStorageState() before doing this.

		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				FolderName);
		// This location works best if you want the created images to be shared
		// between applications and persist after your app has been uninstalled.

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("MyCameraApp", "failed to create directory");
				// return null;
				mediaStorageDir = new File(Environment.DIRECTORY_PICTURES);
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		File mediaFile = new File(mediaStorageDir.getPath() + File.separator
				+ "IMG_" + timeStamp + ".jpg");

		try {
			Boolean res = mediaFile.createNewFile();
			Log.d("Camera", res.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return mediaFile;
	}

	/**
	 * Converts time diff (in msc) to readable string.
	 * 
	 * @param timeDiff
	 * @return
	 */
	public static String getRoughStringForTimeDiff(long timeDiff) {

		timeDiff = Math.max(0, timeDiff);

		long sec = timeDiff / 1000;
		long min = sec / 60;
		long hr = min / 60;
		long days = hr / 24;

		String sDays = "";
		if (days > 0) {
			sDays = String.format("%dd", days);
		}

		String sHr = "";
		if (hr > 0) {
			sHr = String.format("%dh", hr % 24);
		}

		String sMin = "";
		if (min > 0) {
			sMin = String.format("%dm", min % 60);
		}

		String sSec = String.format("%ds", sec % 60);

		if (days > 0) {
			return sDays + sHr;
		}

		if (hr > 0) {
			return sHr + sMin;
		}

		return sMin + sSec;
	}
	
	public static String getDayDiffFromNowAsString(Date d) {
		Calendar nowCal = Calendar.getInstance();
		Calendar refCal = Calendar.getInstance();
		refCal.setTime(d);
		
		int diff = refCal.get(Calendar.DAY_OF_YEAR) - nowCal.get(Calendar.DAY_OF_YEAR);
		if (diff == 0){
			return null;
		}
		
		if (diff == 1){
			return "tomorrow";
		}
		
		if (diff == -1){
			return "yesterday";
		}
		
		Format formatter = new SimpleDateFormat("MM/dd/yyyy");
		return "on " + formatter.format(d);
	}

	private static char[] hextable = { '0', '1', '2', '3', '4', '5', '6', '7',
			'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	private static String byteArrayToHex(byte[] array) {
		String s = "";
		for (int i = 0; i < array.length; ++i) {
			int di = (array[i] + 256) & 0xFF; // Make it unsigned
			s = s + hextable[(di >> 4) & 0xF] + hextable[di & 0xF];
		}
		return s;
	}

	private static String digest(String s, String algorithm) {
		MessageDigest m = null;
		try {
			m = MessageDigest.getInstance(algorithm);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return s;
		}

		m.update(s.getBytes(), 0, s.length());
		return byteArrayToHex(m.digest());
	}

	public static String md5(String s) {
		return digest(s, "MD5");
	}

	public static int getScreenWidth(Activity activity) {
		DisplayMetrics metrics = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
		return metrics.widthPixels;
	}
}
